<?php
session_save_path('../../sessions');
session_start();

// Include the different user types so we can filter out unauthorized users
include("../dbUserTypes.php");

// Include our user class
include_once("../user.php");

// Create a variable to store our user if we're validated
$user = null;

// Check if we're in a valid session. If not, go back to main login page.
if( !isset($_SESSION['user']) || $_SESSION['user'] == null ) {
    header("location:main_login.php");
}
else {
    // Unserialize our user to turn it back into a useful object
    $user = unserialize($_SESSION['user']);
}

// If we're not an admin go back to the user redirection page
if( $user->getUserType() != $USERTYPE_ADMIN ) {
    header("location:login_success.php");
}
else
{    
    // If the deleteID SHA doesn't match the SHA created from the form, then something
    // suspicious is happening and we go back to the routing page
    // This also serves as a partial SQL injection preventer
    if( strcmp($_POST['deleteID'], sha1($_POST['username'].$_POST['id'])) != 0 )
    {
        // Make sure the same activation can't be performed again until you go back to the managing page
        header("location:../../admin_manageUsers.php");
    }

    // Connect to our database
    include("../dbconnection.php");
    
    // User table deletion
    $deleteFromUser_query = "DELETE FROM $TABLE_USERS WHERE $TABLE_USERS_USERID = ".$_POST['id'];
    mysql_query($deleteFromUser_query);
    
    // Delete from user-specific tables
    if( $_POST['type'] == $TABLE_USERTYPE_TYPEREGISTERED)
    {
        // Delete from registered users table
        $deleteRegUser_query = "DELETE FROM $TABLE_REGISTEREDUSER WHERE $TABLE_REGISTEREDUSER_USERID = ".$_POST['id'];
        mysql_query($deleteFromUser_query);
        
        // Delete the user's homes
        $deleteRegUser_query = "DELETE FROM $TABLE_HOME WHERE $TABLE_HOME_HOMEID IN (SELECT $TABLE_LIST_HOMEID FROM $TABLE_LIST WHERE $TABLE_LIST_USERID = ".$_POST['id'].")";
        mysql_query($deleteFromUser_query);
        
        // Delete the list entries
        $deleteRegUser_query = "DELETE FROM $TABLE_LIST WHERE $TABLE_LIST_USERID = ".$_POST['id'];
        mysql_query($deleteFromUser_query);        
    }
    else if( $_POST['type'] == $TABLE_USERTYPE_TYPEBUSINESS)
    {
        // Delete from businessuser table
        $deleteBusinessUser_query = "DELETE FROM $TABLE_BUSINESSAGENT WHERE $TABLE_BUSINESSAGENT_USERID = ".$_POST['id'];
        mysql_query($deleteBusinessUser_query);                
    }
    else if( $_POST['type'] == $TABLE_USERTYPE_TYPEFINANCIAL)
    {
        // Delete from financialuser table
        $deleteFinancialUser_query = "DELETE FROM $TABLE_FINANCIALUSER WHERE $TABLE_FINANCIALUSER_USERID = ".$_POST['id'];
        mysql_query($deleteFinancialUser_query);        
    }
    

    // Close the connection
    mysql_close();


    // Go back to where we were
    header("location:../../admin_manageUsers.php");
}
    